﻿using System.IO;
using DBFile.Core.Impl;
using DBFile.WcfFileProvider.Interfaces;
using System.ServiceModel;

namespace DBFile.Wcf
{
    [ServiceBehavior(
       InstanceContextMode = InstanceContextMode.Single,
       ConcurrencyMode = ConcurrencyMode.Multiple,
#if DEBUG
        IncludeExceptionDetailInFaults = true,
#else
        IncludeExceptionDetailInFaults = false,
#endif
     AddressFilterMode = AddressFilterMode.Any)]
    public class FileService : IFileProvider
    {
        public bool Exists(string filename)
        {
            return DBFile.Core.DBFile.Exists(filename);
        }

        public int Copy(string sourceFilename, string destinationFilename, bool overwrite)
        {
            return DBFile.Core.DBFile.Copy(sourceFilename, destinationFilename, overwrite);
        }

        public int Insert(string filename, byte[] buffer, string contentType, long contentLength, bool overwrite)
        {
            return DBFile.Core.DBFile.Save(filename, buffer, contentType, contentLength, overwrite);
        }

        public int Update(string filename, byte[] buffer, string contentType, long contentLength)
        {
            return DBFile.Core.DBFile.Save(filename, buffer, contentType, contentLength, true);
        }

        public int Delete(string filename)
        {
            return DBFile.Core.DBFile.Delete(filename);
        }

        public string[] GetFileNameList()
        {
            return DBFile.Core.DBFile.GetFileNameList();
        }

        public DBFileInfo Get(string filename)
        {
            DBFileInfo result = new DBFileInfo();
            using (MemoryStream ms = (MemoryStream)DBFile.Core.DBFile.Open(filename))
            {
                int length = (int)ms.Length;

                result.FileBytes = new byte[length];
                ms.Read(result.FileBytes, 0, length);
                ms.Flush();
             
                result.ContentType = DBFile.Core.DBFile.GetContentType(Path.GetExtension(filename));
                result.ContentLength = ms.Length;
                result.FileName = filename;
            }
            return result;
        }

    }
}
